import { cloneDeep,isFunction } from "lodash";
import message from '@/logic/message';

const lifecycleMethods=['onLoad','onShow','onHide','onReady','onUnload','onPageScroll'];

class Page{
    constructor(pageModule,extraOption){
        this.pageModule = pageModule;
        this.extraOption = extraOption;
        this.id=extraOption.id;
        this.data=cloneDeep(pageModule.moduleInfo.data);
        this.initLifecycle();
        this.initMethods();
        this.onLoad(this.extraOption.query || {});
        this.onShow();
    }

    //初始化生命周期函数
    initLifecycle(){
        lifecycleMethods.forEach(name => {
            if(!isFunction(this.pageModule.moduleInfo[name])){
                return false;
            }
            //bind指向当前this
            this[name]= this.pageModule.moduleInfo[name].bind(this);
            
        });
    }
    //初始化自定义函数
    initMethods(){
        const moduleInfo = this.pageModule.moduleInfo;
        for(let attr in moduleInfo){
            if(!isFunction(moduleInfo[attr]) && !lifecycleMethods.includes(attr)){
                continue;
            }
            this[attr]=moduleInfo[attr].bind(this);
        }
    }
    setData(data){
        for(let attr in data){
            this.data[attr]=data[attr];
        }
        message.send({
            type:'updateModule',
            body:{
                id:this.id,
                data:this.data,
                bridgeId:this.id,
            }
        })
    }


}
export {Page};